import { router } from '../index'
import { cloneDeep } from 'lodash-es'
import { base } from '@/api/public'
import { asyncPermitRoutes } from './routeOperate'
import { asyncPermitMenu } from './menuOperate'
import { useRouteMenuStoreWithOut } from '@/store/routeMenu/routeMenuStore'
import { useUserInfoStoreWithOut } from '@/store/storage/userInfoStore'
import { constantRoutes } from '../constantRoutes'
import { resetRouterRedirect } from './public'
import { storeToRefs } from 'pinia'
const routeMenuStore = useRouteMenuStoreWithOut()
const userInfoStore = useUserInfoStoreWithOut()

// 初始化路由
export const initRouter = () => {
  const asyncRouteList = constantRoutes.filter((item) => {
    return item.permit
  })
  const { userInfo } = storeToRefs(userInfoStore)
  return new Promise(async (resolve) => {
    let menuList = []
    let permitList = []
    // 正常后端请求不需要传用户id，后端能判断当前请求的是哪个用户
    // 获取菜单数据 1
    const res: any = await base.menu({ id: userInfo.value.id }, { config: { showLoading: false, mockEnable: true } })
    if (res && res.status) {
      menuList = res.data
    }
    // 获取用户权限 2
    if (asyncRouteList.length > 0) {
      const res2: any = await base.permit({ id: userInfo.value.id }, { config: { showLoading: false, mockEnable: true } })
      if (res2 && res2.status) {
        permitList = res2.data
      }
    }
    // 根据菜单数据及用户权限设置路由数据 3
    const routeList = asyncPermitRoutes(cloneDeep(menuList), permitList)
    if (routeList.length > 0) {
      // 重新设置已实例化路由的重定向路由
      resetRouterRedirect(router, routeList)
      routeList?.map((v: any, idx) => {
        if (v.meta.isRoot) {
          // 防止重复添加路由
          if (router.options.routes.findIndex((value) => value.path === v.path) !== -1) {
            return
          } else {
            if (!router.hasRoute(v?.name)) router.addRoute(v)
            router.options.routes = router.options.routes.concat(v)
          }
        } else {
          const index = router.options.routes.findIndex((v) => v.name === 'Layout')
          // 防止重复添加路由
          if (router.options.routes[index].children.findIndex((value) => value.path === v.path) !== -1) {
            return
          } else {
            if (!router.hasRoute(v?.name)) router.addRoute('Layout', v)
            router.options.routes[index].children.splice(idx, 0, v)
          }
        }
      })
    }
    // 根据菜单数据及用户权限设置菜单数据 4
    routeMenuStore.getRouteMenuList(asyncPermitMenu(cloneDeep(menuList), permitList))
    // 404匹配规则需在最后加入到路由实例中
    router.addRoute({ path: '/:pathMatch(.*)', redirect: '/Exception/404', name: '404' })
    resolve(router)
  })
}
